﻿#include "cameraview.h"
#include "ui_cameraview.h"
#include <QMessageBox>
#include <QDebug>
#define sysdebug qDebug()
Q_DECLARE_METATYPE(QCameraInfo) //使QVariant类支持QCameraInfo类型

CameraView::CameraView(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::CameraView)
{
    ui->setupUi(this);
    setWindowTitle("Camera Viewer");
    setWindowFlags(Qt::FramelessWindowHint | windowFlags());
    setAttribute(Qt::WA_TranslucentBackground);

    //可用的camera设备列表
    const QList<QCameraInfo> availableCameras = QCameraInfo::availableCameras();
    //设备列表添加至设备列表
    for (const QCameraInfo& cameraInfo : availableCameras) {
        ui->cameraList->addItem(cameraInfo.description(), QVariant::fromValue(cameraInfo));
    }
    setCamera(QCameraInfo::defaultCamera());
}

CameraView::~CameraView()
{
    delete ui;
}

void CameraView::closeEvent(QCloseEvent *event)
{
    if(m_camera->state() == QCamera::ActiveState)
    {
        m_camera->stop();
    }
}

void CameraView::setCamera(const QCameraInfo &cameraInfo)
{
    m_camera.reset(new QCamera(cameraInfo));

    connect(m_camera.data(), &QCamera::stateChanged, this, &CameraView::updateCameraState);
    connect(m_camera.data(), QOverload<QCamera::Error>::of(&QCamera::error), this, &CameraView::displayCameraError);

    m_imageCapture.reset(new QCameraImageCapture(m_camera.data()));

    m_camera->setViewfinder(ui->cameraView);

    updateCameraState(m_camera->state());
    updateLockStatus(m_camera->lockStatus(), QCamera::UserRequest);

    connect(m_imageCapture.data(), &QCameraImageCapture::readyForCaptureChanged, this, &CameraView::readyForCapture);
    connect(m_imageCapture.data(), &QCameraImageCapture::imageCaptured, this, &CameraView::icaptrued);
    connect(m_imageCapture.data(), &QCameraImageCapture::imageSaved, this, &CameraView::fcaptrued);

    connect(m_imageCapture.data(), QOverload<int, QCameraImageCapture::Error, const QString &>::of(&QCameraImageCapture::error),
            this, &CameraView::displayCaptureError);

    connect(m_camera.data(), QOverload<QCamera::LockStatus, QCamera::LockChangeReason>::of(&QCamera::lockStatusChanged),
            this, &CameraView::updateLockStatus);

    m_camera->setCaptureMode(QCamera::CaptureStillImage);    //抓图模式
//    m_camera->start();
}
//更新设备状态
void CameraView::updateCameraState(QCamera::State state)
{
    switch (state) {
    case QCamera::ActiveState:
        ui->openCamera->setEnabled(false);
        ui->closeCamera->setEnabled(true);
        ui->cameraSetup->setEnabled(true);
        ui->ActGrabImage->setEnabled(true);
        break;
    case QCamera::UnloadedState:
    case QCamera::LoadedState:
        ui->openCamera->setEnabled(true);
        ui->closeCamera->setEnabled(false);
        ui->cameraSetup->setEnabled(false);
        ui->ActGrabImage->setEnabled(false);
    }
}

void CameraView::displayCameraError()
{
    QMessageBox::warning(this, tr("Camera Error"), m_camera->errorString());
}

void CameraView::updateLockStatus(QCamera::LockStatus status, QCamera::LockChangeReason reason)
{
    switch (status) {
    case QCamera::Searching:    //表示相机正在对焦或正在计算曝光和白平衡
        ui->label->setText("Focusing...");
        break;
    case QCamera::Locked:   //相机的对焦、曝光或白平衡被锁定
        ui->label->setText("Focused");
        break;
    case QCamera::Unlocked: //相机的对焦、曝光或白平衡未被锁定
        if (reason == QCamera::LockFailed)
            ui->label->setText("Focus Failed");
        break;
    }
}

void CameraView::readyForCapture(bool ready)
{
    Q_UNUSED(ready);
}

void CameraView::displayCaptureError(int id, const QCameraImageCapture::Error error, const QString &errorString)
{
    Q_UNUSED(id);
    Q_UNUSED(error);
    QMessageBox::warning(this, tr("Image Capture Error"), errorString);
}

void CameraView::on_cameraSetup_clicked()
{
    ImageSettings settingsDialog(m_imageCapture.data());
    settingsDialog.setWindowFlags(settingsDialog.windowFlags() & ~Qt::WindowContextHelpButtonHint);

    settingsDialog.setImageSettings(m_imageSettings);

    if (settingsDialog.exec()) {
        m_imageSettings = settingsDialog.imageSettings();
        m_imageCapture->setEncodingSettings(m_imageSettings);
    }
}

void CameraView::on_exposure_valueChanged(int value)
{
    m_camera->exposure()->setExposureCompensation(value*0.5);
}

void CameraView::on_openCamera_clicked()
{
    m_camera->start();
}

void CameraView::on_closeCamera_clicked()
{
    m_camera->stop();
}

void CameraView::on_cameraList_currentIndexChanged(int index)
{
    static int last_index = 0;
    if(index != last_index)
    {
        m_camera->stop();
        setCamera(ui->cameraList->itemData(index).value<QCameraInfo>());
    }
    last_index = index;
}

void CameraView::on_ActGrabImage_clicked()
{
    captrueImage();
}

void CameraView::openCamera()
{
    if(m_camera->state() == QCamera::ActiveState)
    {
        return;
    }
    m_camera->start();
}
void CameraView::closeCamera()
{
    if(m_camera->state() == QCamera::ActiveState)
    {
        m_camera->stop();
    }
}
void CameraView::captrueImage()
{
    m_imageCapture->capture(qApp->applicationDirPath() + "/captrue/" + QString::number(QDateTime::currentDateTime().toMSecsSinceEpoch()));
}
